package com.ttdev.mmms.controller.recharge;
import com.ttdev.mmms.entity.Account;
import com.ttdev.mmms.entity.MemberInfo;
import com.ttdev.mmms.repository.MemberRepository;
import com.ttdev.mmms.service.MemberService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 杨培朔
 * 管理员给会员充值
 * 2019年12月24日17:06:16
 */
@Controller
@RequestMapping("/storeRecharge")
public  class StoreRechargeController {

    @Autowired
    private MemberRepository memberRepository;

    // 跳转充值页面
    @RequestMapping("/recharge")
    public String MemberPayment(){
        return "store/storeRecharge";
    }

    // 查询会员卡号
    @RequestMapping(value = "/select", produces = "application/json;charset=UTF-8")
    public void SelectCard(@RequestParam Integer card, HttpServletResponse response) throws IOException {

//        System.out.println(card);
        List<MemberInfo> list = new ArrayList<>();
        list = memberRepository.queryMember(card);
        JSONArray jsonArray = JSONArray.fromObject(list);
        // json乱码解决
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(jsonArray.toString());

    }

    // 给会员充值
    @RequestMapping("/pm")
    public void payment(@RequestParam Integer card, @RequestParam Double price,@RequestParam Integer storeId,HttpServletResponse response) throws IOException {
//        System.out.println(price);
//        System.out.println(card);

        // 扣款
        int i = memberRepository.updateBalance(price,card);
//        System.out.println(i);

        //入账
        Account account = new Account();
        account.setCardId(card);
        account.setStoreId(storeId);
        account.setMoney(price);
        account.setType("充值");
//        System.out.println(account.getCardId());
        int cardId = account.getCardId();
        int sId = account.getStoreId();
        double money = account.getMoney();
        String type = account.getType();
        int acc = memberRepository.account(cardId,sId,money,type);

        if (i != 0){
            JSONObject obj = new JSONObject();
            obj.put("i", i);
            obj.put("acc",acc);
//        System.out.println(obj);
            response.getWriter().write(obj.toString());
        }
    }
}
